package com.kakaxi.mybilibili.net;

import com.vincestyling.netroid.AuthFailureError;
import com.vincestyling.netroid.DefaultRetryPolicy;
import com.vincestyling.netroid.IListener;
import com.vincestyling.netroid.NetroidLog;
import com.vincestyling.netroid.request.StringRequest;

import java.io.UnsupportedEncodingException;

/**
 * 带缓存区分的网页请求
 * Created by kakaxi on 16/11/25.
 */

public class StringCacheRequest extends StringRequest {

    /** 同一个请求缓存的分页标识 **/
    private String mRequestCacheTag = "";

    /** 请求内容 **/
    private String mRequestBody;

    /**
     * 初始化
     *
     * @param method          请求类型
     * @param url             请求链接
     * @param requestBody     请求内容
     * @param listener        监听器
     * @param requestCacheTag 缓存标签
     */
    public StringCacheRequest(int method, String url, String requestBody, IListener<String>
            listener, String requestCacheTag) {
        super(method, url, listener);
        mRequestBody = requestBody;
        mRequestCacheTag = requestCacheTag;
        // 设置请求默认10秒超时, 重试请求1次
        setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public StringCacheRequest(int method, String url, String requestBody, IListener<String>
            listener) {
        this(method, url, requestBody, listener, "");
    }

    public StringCacheRequest(String url, String requestBody, IListener<String> listener) {
        this(requestBody == null ? Method.GET : Method.POST, url, requestBody, listener);
    }


    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return this.mRequestBody == null ? null : this.mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException var2) {
            NetroidLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    new Object[]{this.mRequestBody, "utf-8"});
            return null;
        }
    }

    @Override
    public String getCacheKey() {
        if (mRequestCacheTag != null) {
            return super.getCacheKey() + mRequestCacheTag;
        }
        return super.getCacheKey();
    }

}
